package com.jmp.security.grant;

import com.jmp.security.base.ClientDetail;
import com.jmp.security.base.RequestDetail;
import com.jmp.security.base.UserDetail;
import lombok.extern.slf4j.Slf4j;
import one.stand.advice.ResultEnum;
import one.stand.mapper.CompanyMapperExt;
import one.stand.mapper.CompanyPlatformMapperServiceLoginExt;
import one.stand.model.BusinessCard;
import one.stand.model.CompanyPlatform;
import one.stand.model.SysDictValue;
import one.stand.service.BusinessCardBaseService;
import one.stand.service.sys.SysDictValueService;
import one.stand.util.AssertUtil;

import java.util.Objects;

@Slf4j
public class CompanyKeyUserDetailValidServiceImpl<T extends RequestDetail> extends UserDetailValidServiceImpl<T> {
    private CompanyPlatformMapperServiceLoginExt companyPlatformMapperServiceLoginExt;
    private SysDictValueService sysDictValueService;

    public CompanyKeyUserDetailValidServiceImpl(BusinessCardBaseService businessCardBaseService, CompanyMapperExt companyMapperExt, CompanyPlatformMapperServiceLoginExt companyPlatformMapperServiceLoginExt, SysDictValueService sysDictValueService) {
        super(businessCardBaseService, companyMapperExt);
        this.companyPlatformMapperServiceLoginExt = companyPlatformMapperServiceLoginExt;
        this.sysDictValueService = sysDictValueService;
    }

    @Override
    public void check(T requestDetail, ClientDetail clientDetail, UserDetail userDetail) {
        super.check(requestDetail, clientDetail, userDetail);

        BusinessCard businessCard = userDetail.getCardModel();
        if (Objects.nonNull(businessCard)) {
            if (businessCard.getAuditState() != 1) {//名片未审核通过
                userDetail.setCardModel(null);
                userDetail.setCompany(null);
            } else {
                SysDictValue sysDictValue = sysDictValueService.get(SysDictValueService.Type.default_company_key, SysDictValueService.TypeName.default_company_key);
                if (!requestDetail.getCompanyKey().equals(sysDictValue.getValue())) {// 不是默认平台时，检查平台归属
                    CompanyPlatform companyPlatform = companyPlatformMapperServiceLoginExt.selectPlatformByCompanyId(businessCard.getCompanyId());
                    AssertUtil.isTrue(Objects.nonNull(companyPlatform) && companyPlatform.getCompanyKey().equals(requestDetail.getCompanyKey()), ResultEnum.PARAM_CHECK, "未加入该平台，请联系客服");
                }
            }
        }
    }
}
